package homework.chattwo;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ChatClientTwo01 {
    private static Socket socket;

    public ChatClientTwo01() {
        try {
            socket = new Socket("127.0.0.1", 8888);
            System.out.println("连接成功...");
        } catch (IOException e) {
            System.out.println("连接失败...");
            e.printStackTrace();
            System.exit(1);
        }
    }

    class ServerHandler implements Runnable {

        @Override
        public void run() {
            BufferedReader br=null;
            try {
                 br = new BufferedReader(
                        new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));

                String data;
                while (true) {
                    if ((data = br.readLine()) != null) {
                        System.out.println(data);
                    }
                }
            } catch (IOException e) {
                try {
                    br.close();
                    socket.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    public void start() {
        PrintWriter pw = null;
        Scanner scanner = new Scanner(System.in);

        try {
            pw = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8)), true);

            while (true){
                System.out.println("输入用户名:");
                String userName = scanner.nextLine();
                if (userName.trim().isEmpty()){
                    System.out.println("用户名不能为空");
                    continue;
                }
                pw.println(userName);
                break;
            }

            new Thread(new ServerHandler()).start();
            System.out.println("发送消息:");
            while (true) {
                String send = scanner.nextLine();
                if ("exit".equalsIgnoreCase(send)) {
                    System.out.println("退出聊天室...");
                    break;
                }
                pw.println(send);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (pw!=null)pw.close();
            if (scanner!=null)scanner.close();
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


    }

    public static void main(String[] args) {
        new ChatClientTwo01().start();
    }

}
